我想自动推断出我正在编写的函数的返回类型.例:
std::vector<int> test(){
decltype(this_function) ret;
ret.push_back(5);
ret.push_back(9);
return ret;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我所取得的成就是最好的
std::vector<int> test(){
decltype(test()) ret;
ret.push_back(5);
ret.push_back(9);
return ret;
}
Run Code Online (Sandbox Code Playgroud)
这可以,但是:
如果我改变功能名称,我必须改变
decltype(试验())
成
decltype(名称())
如果我改变功能参数,我也必须改变
decltype(试验())
成
decltype(试验(参数1,参数2))
是否有更优雅的方式做同样的事情?
我一直在测试一些C++ 11的一些功能.我遇到了r值引用并移动构造函数.
我实现了我的第一个移动构造函数,这里是:
#include <iostream>
#include <vector>
using namespace std;
class TestClass{
public:
TestClass(int s):
size(s), arr(new int[s]){
}
~TestClass(){
if (arr)
delete arr;
}
// copy constructor
TestClass(const TestClass& other):
size(other.size), arr(new int[other.size]){
std::copy(other.arr, other.arr + other.size, arr);
}
// move constructor
TestClass(TestClass&& other){
arr=other.arr;
size=other.size;
other.arr=nullptr;
other.size=0;
}
private:
int size;
int * arr;
};
int main(){
vector<TestClass> vec;
clock_t start=clock();
for(int i=0;i<500000;i++){
vec.push_back(TestClass(1000));
}
clock_t stop=clock();
cout<<stop-start<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码工作正常.无论如何把一个std :: cout放在复制构造函数中我注意到它被调用了!并且很多次..(移动构造函数500000次,复制构造函数524287次).
让我感到惊讶的是,如果我从代码中注释掉复制构造函数,整个程序会更快,而这次移动构造函数被称为1024287次.
任何线索?
我已经读过创建或复制std :: shared_ptr涉及一些开销(参考计数器的原子增量等).
但是如何从它创建一个std :: weak_ptr:
Obj * obj = new Obj();
// fast
Obj * o = obj;
// slow
std::shared_ptr<Obj> a(o);
// slow
std::shared_ptr<Obj> b(a);
// slow ?
std::weak_ptr<Obj> c(b);
Run Code Online (Sandbox Code Playgroud)
我希望在一些更快的性能,但我知道共享指针仍然必须递增弱引用计数器..所以这仍然像将shared_ptr复制到另一个慢?
我需要存储一个指向对象的指针的容器。这些对象有一些我想要强制执行(可能在编译时)和使用的通用方法/属性(接口)。例子:
struct A{
void fly(){}
};
struct B{
void fly(){}
};
A a;
B b;
std::vector<some *> objects;
objects.push_back(&a);
objects.push_back(&b);
for(auto & el: objects)
el->fly();
Run Code Online (Sandbox Code Playgroud)
更简单的解决办法是A和B继承公共基类一样FlyingClass:
struct FlyingClass{
void fly(){}
};
struct A: public FlyingClass { ...
struct B: public FlyingClass { ...
Run Code Online (Sandbox Code Playgroud)
并创建一个
std::vector<FlyingClass *> objects;
Run Code Online (Sandbox Code Playgroud)
这将起作用并强制执行我只能添加到objects可以飞行的东西(实现FlyingClass)的事实。
但是如果我需要实现一些其他常见的方法/属性而不将它们与上述基类耦合呢?
例子:
struct A{
void fly(){}
void swim(){}
};
struct B{
void fly(){}
void swim(){}
};
Run Code Online (Sandbox Code Playgroud)
我想做:
for(auto & el: objects) { …Run Code Online (Sandbox Code Playgroud) c++ ×4
c++11 ×2
decltype ×1
interface ×1
oop ×1
performance ×1
polymorphism ×1
shared-ptr ×1
templates ×1
types ×1
weak-ptr ×1