Xcode5-DP3 (5A11344j): C++11 lambda closures can capture references to abstract classes by value, instantiating the abstract class at runtime

Originator:Karoly.Lorentey
Number:rdar://14468891 Date Originated:17-Jul-2013 05:45 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode5-DP3 (5A11344j)
Classification:Other Bug Reproducible:Always
 
Summary:

Clang 4.2 and 5.0 successfully compiles C++ lambdas that are capturing local reference variables by value even if the variable's type is an abstract class. At runtime, the abstract class is instantiated via its copy constructor when the closures are initialized, leading to pure virtual method calls and, thus, crashes.

Steps to Reproduce:

Try compiling the following (illegal) sample code:

	#import <string>
	#import <iostream>

	class Abstract
	{
	public:
	    virtual ~Abstract() {};
	    virtual std::string Foo() const = 0;
	};

	class Concrete : public Abstract
	{
	public:
	    std::string Foo() const override { return "Concrete"; }
	};

	int main(int argc, const char * argv[])
	{
	    
	    Concrete c;
	    Abstract &aref = c;
	    
	    std::cout << c.Foo() << std::endl;
	    std::cout << aref.Foo() << std::endl;
	    
	    auto lambda = [aref]{  // Clang should refuse to compile this line
	        std::cout << aref.Foo() << std::endl;
	    };
	    lambda();
	    return 0;
	}

Expected Results:

A compile-time error message complaining that the [aref] capture scope instantiates an abstract base class.

Actual Results:

The (illegal) code compiles successfully crashes at runtime:

$ clang --version
Apple LLVM version 5.0 (clang-500.1.61) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix
$ clang -std=c++11 -stdlib=libc++ -lc++ main.cpp
$ /a.out 
Concrete
Concrete
libc++abi.dylib: pure virtual method called
fish: Job 1, './a.out ' terminated by signal SIGABRT (Abort)

Regression:
Unknown; Clang 4.2 in Xcode 4.6.3 has the same issue.

Notes:

Also see rdar://14261999 for a somewhat similar issue in Objective-C++.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!