Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created Apr 8, 2015
Embed
What would you like to do?
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