Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created April 8, 2015 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/a43dccab86b92aa6faa9 to your computer and use it in GitHub Desktop.
Save rayfix/a43dccab86b92aa6faa9 to your computer and use it in GitHub Desktop.
How to construct C++11
//
// main.cpp
// forward
//
// Created by Ray Fix on 4/8/15.
// Copyright (c) 2015 Pelfunc, Inc. All rights reserved.
//
#include <iostream>
class MyClass {
public:
// The old way
// MyClass(const std::string& name) : name_(name) {}
// New way #1: I think this way wins!
MyClass(std::string name) : name_(std::move(name)) {}
// New way #2: thanks davidstone
// MyClass(const std::string& name) : name_(name) {}
// MyClass(const std::string&& name) : name_(name) {}
// New way #3 thanks davidstone
// template<typename T>MyClass(T && name): name_(std::forward<T>(name)) {
// static_assert(std::is_same<T, std::string>::value, "name must be a std::string");
// }
private:
std::string name_;
};
int main(int argc, const char * argv[]) {
auto foo = MyClass("foo");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment